#include "keyboardcompwidget.h"
#include "keybutton.h"
#include "keychooserdelegate.h"


KeyboardCompWidget::KeyboardCompWidget(AED_KeyboardComp *comp, QWidget *parent) :
    QWidget(parent),m_comp(comp)
{

    QVBoxLayout *layout = new QVBoxLayout;
    this->setLayout(layout);

    group = new QGroupBox("Enable");
    layout->addWidget(group);
    group->setCheckable(true);


    QVBoxLayout *main_layout = new QVBoxLayout; // La layout principal
    group->setLayout(main_layout);

    QHBoxLayout *button_layout = new QHBoxLayout;
    main_layout->addLayout(button_layout);

    add_cond_button = new QPushButton("Add Condition");
    remove_cond_button = new QPushButton("Remove Condition");
    button_layout->addWidget(add_cond_button);
    button_layout->addWidget(remove_cond_button);

    m_model = 0;
    m_condtable = new QTableView();

    m_condtable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_condtable->resizeColumnsToContents();
    m_condtable->setItemDelegateForColumn(1,new KeyChooserDelegate);

    m_condtable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
    main_layout->addWidget(m_condtable);


    connect(group, SIGNAL(toggled(bool)),
                this,SLOT(SetEnabled(bool)));

    setComp(comp);

}

void KeyboardCompWidget::setComp(AED_KeyboardComp *comp){
    m_comp = comp;
    if(!m_comp){
        group->setEnabled(false);
    }else{
        disconnect(add_cond_button);
        disconnect(remove_cond_button);

        group->setEnabled(true);
        group->setChecked(comp->IsEnabled());

        if(m_model)
            delete m_model;
        m_model = new KeyboardCondModel(m_comp);
        m_condtable->setModel(m_model);
        connect(add_cond_button, SIGNAL(pressed()),
                    m_model,SLOT(AddCondition()));
        connect(remove_cond_button, SIGNAL(pressed()),
                    this,SLOT(RemoveCondition()));
    }
}

void KeyboardCompWidget::SetEnabled(bool enabled){
    m_comp->SetEnabled(enabled);
}

void KeyboardCompWidget::ResizeColumns(){
    m_condtable->resizeColumnsToContents();
}

void KeyboardCompWidget::RemoveCondition(){
    QModelIndexList lstIndex ;

    QItemSelection ranges = m_condtable->selectionModel()->selection();
    for (int i = 0; i < ranges.count(); ++i){
        QModelIndex parent = ranges.at(i).parent();
        int right = ranges.at(i).model()->columnCount(parent) - 1;
        if (ranges.at(i).left() == 0 && ranges.at(i).right() == right)
            for (int r = ranges.at(i).top(); r <= ranges.at(i).bottom(); ++r)
                lstIndex.append(ranges.at(i).model()->index(r, 0, parent));
    }
    for(int i=0; i<lstIndex.size();i++){
        QModelIndex index = lstIndex.at(i);
        if(index.isValid()){
            m_model->RemoveCondition(index.row());
        }
    }
}

